﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DcsGauges.Shared.Network;
using DcsGauges.Shared.Packets;
using NLog;

namespace DcsGauges.Server.Network
{
    class DataDispatcher
    {
        #region Readonly & Constants

        private static readonly Logger              logger                  = LogManager.GetCurrentClassLogger();

        #endregion

        #region Fields & Properties

        private IGameChannel                        dataSource;
        
        private List<IDcsGaugesClientChannel>       dataSinks               = new List<IDcsGaugesClientChannel>();
        public List<IDcsGaugesClientChannel>        DataSinks
        {
            get { return this.dataSinks; }
        }

        public IGameChannel DataSource
        {
            get { return this.dataSource; }
        }

        #endregion


        #region Operations

        public void SetDataSource(IGameChannel gc)
        {
            this.dataSource                             = gc;
            this.dataSource.DataPacketReceivedEvent     += OnDataPacketReceivedEvent;
        }

        public void RegisterDataSink(IDcsGaugesClientChannel cc)
        {
            this.dataSinks.Add(cc);
            cc.CommandsPacketReceivedEvent          += new EventHandler<PacketReceivedEventArgs<CommandsPacket>>(OnClientChannelHandleCommandsPacketReceivedEvent);
        }

        #endregion


        #region Event Handlers

        private void OnDataPacketReceivedEvent(object sender, PacketReceivedEventArgs<DataPacket> e)
        {
            foreach(IDcsGaugesClientChannel channel in this.dataSinks)
            {
                channel.Send(e.Packet);
            }
        }

        void OnClientChannelHandleCommandsPacketReceivedEvent(object sender, PacketReceivedEventArgs<CommandsPacket> e)
        {
            if (this.dataSource != null)
            {
                this.dataSource.IssueCommand(e.Packet);
            }
            else
            {
                logger.Log(LogLevel.Error, "Cannot issue command, because no Command-Sink (DataSource) is available");
            }
        }

        #endregion
    }
}
